package cn.dinkevin.xui.watcher;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;

import cn.dinkevin.xui.XUI;
import cn.dinkevin.xui.thread.ThreadExecutor;
import cn.dinkevin.xui.util.LogUtil;

/**
 * 广播
 * Created by ChengPengFei on 2017/2/21 0021.</br>
 * Copyright ©2017 juziwl, All Rights Reserved.
 */

public final class BroadcastWatcher {

    private BroadcastWatcher(){}

    /**
     * 发送全局广播
     * @param intent 广播数据
     */
    public static void sendGlobalBroadcast(Intent intent){
        XUI.getInstance().getContext().sendBroadcast(intent);
    }

    /**
     * 发送本地广播
     * @param intent 广播数据
     */
    public static void sendLocalBroadcast(final Intent intent){
        ThreadExecutor.main(new Runnable() {
            @Override
            public void run() {
                LocalBroadcastManager manager = LocalBroadcastManager.getInstance(XUI.getInstance().getContext());
                manager.sendBroadcast(intent);
                LogUtil.d("send local broadcast",intent.getAction());
            }
        });
    }

    /**
     * 注册全局广播接收
     * @param receiver
     * @param actions 过滤字段
     */
    public static void resigerGlobalReceiver(BroadcastReceiver receiver,String... actions){
        IntentFilter filter = new IntentFilter();
        for(String action : actions){
            filter.addAction(action);
        }
        XUI.getInstance().getContext().registerReceiver(receiver,filter);
    }

    /**
     * 注销全局广播接收
     * @param receiver
     */
    public static void unregisterGlobalReceiver(BroadcastReceiver receiver){
        XUI.getInstance().getContext().unregisterReceiver(receiver);
    }

    /**
     * 注册本地广播接收
     * @param receiver
     * @param actions
     */
    public static void registerLocalBroadcast(BroadcastReceiver receiver,String... actions){
        IntentFilter filter = new IntentFilter();
        for(String action : actions){
            filter.addAction(action);
        }
        LocalBroadcastManager manager = LocalBroadcastManager.getInstance(XUI.getInstance().getContext());
        manager.registerReceiver(receiver,filter);
    }

    /**
     * 注销本地广播接收
     * @param receiver
     */
    public static void unregisterLocalReceiver(BroadcastReceiver receiver){
        LocalBroadcastManager manager = LocalBroadcastManager.getInstance(XUI.getInstance().getContext());
        manager.unregisterReceiver(receiver);
    }
}
